import { Provide } from "@midwayjs/decorator";
import { InjectEntityModel} from '@midwayjs/typegoose';
import { ReturnModelType } from '@typegoose/typegoose';
import { LogsFlat } from '../entity/logflat';
import { LogsContent, QueryLogsParam } from '../interface'
import queue from 'queue';
const saveLosQueue = new queue({ autostart: true, concurrency: 1 });

@Provide()
export class FlatLogsHandlerService {

    @InjectEntityModel(LogsFlat)
    logsFlatModel: ReturnModelType<typeof LogsFlat>; // 返回 一个 Tree 集合类型

    /**
     * 处理xlog发来的日志
     * @param logsContent 
     */
     restoreLog(logsContent: LogsContent) : boolean{
        
        saveLosQueue.push( async cb => {
            await this.uploadLogs({
                ...logsContent,
                project_name: logsContent.projectName,
                logs_name: logsContent.logsName,
                logs: logsContent.logsContent,
                category: logsContent.category.join('_'),
                date: new Date(logsContent.time)
            });
            cb();
        })

        return true;
    }

    /**
     * 获取 日志信息
     * @param params 
     */
    async getLogs(params: QueryLogsParam): Promise<Array<LogsFlat> | boolean | any> {

        const { start_time, end_time } = params;
        let query: any = {
            project_name: params.project_name,
            category: params.category,
            type: params.type,
            logs_name: params.logs_name,
        }

        // time
        if (start_time && end_time) {
            query.date = { $lt: end_time, $gt: start_time }
        }

        // 行数
        if (params.rows) {
            query.row = params.rows;
        }

        // 搜索 内容
        if (params.searchContent) {
            query.logs = {$regex: params.searchContent};
        }

        try {

            if (params.sort == -1) {
                // 先查出 所有logs的数量
                let count = await this.logsFlatModel.find(query).count();
                // offset 到最后一项 limit 数量
                let offset = count - params.limit ;
                console.log(offset);
                
                // 查询最后一轮
                let logs = await this.logsFlatModel.find(query).sort({ _id: 1 }).limit(params.limit).skip(offset < 0 ? 0 : offset);
                return {logs, offset};
            }
            return await this.logsFlatModel.find(query).sort({ _id: 1 }).limit(params.limit).skip(params.offset);
        } catch (_) {
            console.log(_);
            return false;
        }
    }

    /**
     * 上传日志
     * @param logsInfo 
     * @returns 
     */
    private async uploadLogs(logsInfo: LogsFlat): Promise<boolean> {

        try {
            const { _id: id } = await this.logsFlatModel.create(logsInfo as LogsFlat);

            console.log(id);
            return true;
        } catch (_) {
            console.log(_);
            return false;
        }
    }
}